<template>
  <view class="add-friend-page">
    <!-- 顶部导航栏 -->
    <view class="header-bar">
      <view class="header-left">
        <button class="back-btn" @click="goBack">← 返回</button>
      </view>
      <view class="header-title">添加好友</view>
      <view class="header-right"></view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-container">
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="输入昵称、UID、手机号、邮箱、姓名或身份证号搜索..." 
          class="search-input"
          @input="onSearchInput"
        />
        <button class="search-btn" @click="searchUsers">搜索</button>
        <button class="test-btn" @click="testAllUsers" style="margin-left: 10px; background: #ff6b6b; color: white; border: none; padding: 8px 12px; border-radius: 4px;">测试</button>
      </view>
      <view class="search-tips">
        <text class="tip-text">💡 支持通过昵称、UID、手机号、邮箱、真实姓名、身份证号搜索用户</text>
      </view>
    </view>

    <!-- 搜索结果 -->
    <view class="search-results-section">
      <view v-if="loading" class="loading-spinner">
        <span class="spinner"></span>
        <text>搜索中...</text>
      </view>
      
      <view v-else-if="searchResults.length" class="results-container">
        <view class="results-title">搜索结果</view>
        <view 
          v-for="user in searchResults" 
          :key="user.id" 
          class="result-item"
        >
          <image :src="getAvatarUrl(user.friendAvatarUrl)" class="result-avatar" @error="handleAvatarError" />
          <view class="result-info">
            <text class="result-name">{{ user.friendNickname }}</text>
            <text class="result-signature">{{ user.signature || '这个人很懒，什么都没写' }}</text>
          </view>
          <view class="action-buttons">
            <!-- 调试信息 -->
            <view class="debug-info" style="font-size: 10px; color: #999; margin-bottom: 4px;">
              <text>ID: {{ user.friendId }} | 当前: {{ currentUserId }} | 状态: {{ user.friendStatus }}</text>
            </view>
            
            <!-- 如果是自己 -->
            <view v-if="Number(user.friendId) === Number(currentUserId)" class="self-indicator">
              <text class="self-text">这是你自己</text>
            </view>
            
            <!-- 如果是好友 -->
            <view v-else-if="user.friendStatus === 'accepted'" class="friend-actions">
              <button class="chat-btn" @click="startChat(user)">聊天</button>
              <button class="delete-btn" @click="deleteFriend(user)">删除好友</button>
            </view>
            
            <!-- 如果已发送好友请求 -->
            <view v-else-if="user.friendStatus === 'pending'" class="pending-indicator">
              <text class="pending-text">好友请求已发送</text>
            </view>
            
            <!-- 如果不是好友 -->
            <view v-else class="add-friend-action">
              <button 
                class="add-friend-btn" 
                @click="sendFriendRequest(user)"
                :disabled="addingFriend"
              >
                {{ addingFriend ? '添加中...' : '添加好友' }}
              </button>
            </view>
          </view>
        </view>
      </view>
      
      <view v-else-if="searchKeyword && !loading" class="no-results">
        <view class="no-results-icon">🔍</view>
        <text class="no-results-title">未找到用户</text>
        <text class="no-results-desc">请检查用户名是否正确</text>
      </view>
      
      <view v-else class="search-tip">
        <view class="tip-icon">👥</view>
        <text class="tip-title">搜索用户</text>
        <text class="tip-desc">输入用户昵称来搜索并添加好友</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, onMounted } from 'vue'
import { getAvatarUrl } from '@/utils/imageUtils.js'
import { useUserStore } from '@/store/user'

// 数据
const loading = ref(false)
const searchKeyword = ref('')
const searchResults = ref([])
const addingFriend = ref(false)
const currentUserId = ref(null)
let searchTimeout = null

// 获取用户store
const userStore = useUserStore()

// 获取当前用户ID
onMounted(() => {
  // 使用userStore获取用户ID
  currentUserId.value = Number(userStore.profile?.uid) || null
  
  console.log('=== 用户ID调试 ===')
  console.log('userStore.profile:', userStore.profile)
  console.log('userStore.profile?.uid:', userStore.profile?.uid)
  console.log('currentUserId.value:', currentUserId.value)
  console.log('currentUserId类型:', typeof currentUserId.value)
  console.log('==================')
})

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 输入处理（防抖）
const onSearchInput = () => {
  // 清除之前的定时器
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  
  // 设置新的定时器，500ms后执行搜索
  searchTimeout = setTimeout(() => {
    searchUsers()
  }, 500)
}

// 搜索用户
const searchUsers = async () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = []
    return
  }

  console.log('开始搜索用户:', searchKeyword.value)
  loading.value = true
  try {
    const token = uni.getStorageSync('accessToken')
    if (!token) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/friends/search?keyword=${encodeURIComponent(searchKeyword.value)}`,
      method: 'GET',
      header: {
        'Access-Token': `Bearer ${token}`
      }
    })

    console.log('搜索响应:', response)
    console.log('响应状态码:', response.statusCode)
    console.log('响应数据:', response.data)
    console.log('响应数据类型:', typeof response.data)
    console.log('响应数据内容:', JSON.stringify(response.data))

    if (response.data && response.data.code === 200) {
      searchResults.value = response.data.data || []
      console.log('搜索结果:', searchResults.value)
      console.log('搜索结果数量:', searchResults.value.length)
      console.log('搜索结果类型:', typeof searchResults.value)
      console.log('搜索结果是否为数组:', Array.isArray(searchResults.value))
      
      // 调试每个用户的状态
      searchResults.value.forEach((user, index) => {
        console.log(`用户${index + 1}:`, {
          friendId: user.friendId,
          friendNickname: user.friendNickname,
          friendStatus: user.friendStatus,
          currentUserId: currentUserId.value,
          isSelf: Number(user.friendId) === Number(currentUserId.value)
        })
      })
      
      if (searchResults.value.length === 0) {
        console.log('没有找到匹配的用户，可能的原因:')
        console.log('1. 数据库中没有匹配的用户')
        console.log('2. 用户隐私设置不允许搜索')
        console.log('3. 用户已经是好友')
        console.log('4. SQL查询条件过于严格')
        
        uni.showToast({
          title: '未找到匹配的用户',
          icon: 'none'
        })
      }
    } else {
      console.error('搜索用户失败:', response.data?.message || '未知错误')
      console.error('错误响应:', response.data)
      uni.showToast({
        title: response.data?.message || '搜索失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    uni.showToast({
      title: '搜索失败，请检查网络连接',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 测试获取所有用户
const testAllUsers = async () => {
  console.log('开始测试获取所有用户')
  loading.value = true
  try {
    const token = uni.getStorageSync('accessToken')
    if (!token) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/friends/test-all-users`,
      method: 'GET',
      header: {
        'Access-Token': `Bearer ${token}`
      }
    })

    console.log('测试接口响应:', response)
    console.log('测试接口响应数据:', response.data)

    if (response.data && response.data.code === 200) {
      const users = response.data.data || []
      console.log('测试接口返回用户数量:', users.length)
      console.log('测试接口返回用户列表:', users)
      
      if (users.length > 0) {
        uni.showToast({
          title: `找到 ${users.length} 个用户`,
          icon: 'success'
        })
      } else {
        uni.showToast({
          title: '数据库中没有其他用户',
          icon: 'none'
        })
      }
    } else {
      console.error('测试接口失败:', response.data?.message || '未知错误')
      uni.showToast({
        title: response.data?.message || '测试失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('测试接口失败:', error)
    uni.showToast({
      title: '测试失败，请检查网络连接',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 发送好友请求
const sendFriendRequest = async (user) => {
  if (addingFriend.value) return
  
  addingFriend.value = true
  try {
    const token = uni.getStorageSync('accessToken')
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/friends/request`,
      method: 'POST',
      header: {
        'Access-Token': `Bearer ${token}`
      },
      data: {
        friendId: user.friendId
      }
    })

    if (response.data && response.data.code === 200) {
      uni.showToast({
        title: '好友请求已发送',
        icon: 'success'
      })
      // 更新用户状态
      user.friendStatus = 'pending'
    } else {
      uni.showToast({
        title: response.data?.message || '发送失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('发送好友请求失败:', error)
    uni.showToast({
      title: '发送失败',
      icon: 'none'
    })
  } finally {
    addingFriend.value = false
  }
}

// 开始聊天
const startChat = (user) => {
  uni.navigateTo({
    url: `/pages/social/chat-detail?userId=${user.friendId}&name=${user.friendNickname}`
  })
}

// 删除好友
const deleteFriend = async (user) => {
  try {
    const token = uni.getStorageSync('accessToken')
    if (!token) {
      uni.showToast({ title: '请先登录', icon: 'none' })
      return
    }
    
    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/friends/${user.friendId}`,
      method: 'DELETE',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    if (response.data && response.data.code === 200) {
      uni.showToast({ title: '已删除好友', icon: 'success' })
      // 更新用户状态
      user.friendStatus = 'not_friend'
    } else {
      uni.showToast({ title: response.data?.message || '删除失败', icon: 'none' })
    }
  } catch (error) {
    console.error('删除好友失败:', error)
    uni.showToast({ title: '删除失败，请检查网络连接', icon: 'none' })
  }
}

// 错误处理
const handleAvatarError = () => {
  console.log('头像加载失败')
}
</script>

<style scoped>
.add-friend-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #4A90E2;
  color: white;
}

.header-left, .header-right {
  flex: 1;
}

.header-title {
  flex: 2;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.back-btn {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  padding: 8px 12px;
  border-radius: 4px;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.search-section {
  padding: 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.search-container {
  display: flex;
  gap: 8px;
}

.search-input {
  flex: 1;
  height: 40px;
  padding: 0 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
}

.search-btn {
  padding: 0 16px;
  height: 40px;
  background: #4A90E2;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
}

.search-tips {
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f6ff;
  border-radius: 8px;
  border-left: 3px solid #4A90E2;
}

.tip-text {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

.search-results-section {
  flex: 1;
  padding: 16px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #4A90E2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.results-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.results-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.result-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-avatar {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  margin-right: 12px;
  object-fit: cover;
}

.result-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.result-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.result-signature {
  font-size: 12px;
  color: #999;
}

.add-friend-btn {
  padding: 8px 16px;
  background: #4A90E2;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  min-width: 80px;
}

.add-friend-btn:disabled {
  background: #ccc;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: flex-end;
}

.self-indicator {
  padding: 8px 12px;
  background: #f0f0f0;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.self-text {
  color: #666;
  font-size: 14px;
}

.friend-actions {
  display: flex;
  gap: 8px;
}

.chat-btn {
  background: #4A90E2;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.delete-btn {
  background: #ff6b6b;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.pending-indicator {
  padding: 8px 12px;
  background: #fff3cd;
  border-radius: 4px;
  border: 1px solid #ffeaa7;
}

.pending-text {
  color: #856404;
  font-size: 14px;
}

.add-friend-action {
  display: flex;
}

.no-results, .search-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.no-results-icon, .tip-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-results-title, .tip-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.no-results-desc, .tip-desc {
  font-size: 14px;
  color: #999;
}
</style>
